
//  DatabaseConnection.m


#import "DatabaseConnection.h"

#import "Items.h"
#import "AppDelegate.h"
#import "Photo.h"
#import "Category.h"
#import "Utilities.h"
#import "CMCUniqueArray.h"

#define TAGS_LIST @"LOL;OMG;WTF;IDK;DERP;AMUSED;NOT AMUSED;FACE PALM;INTERESTING;NO THANKS;GROSS;SAD;MAD;LOVE;DEAL;PROBLEMS;WHATS UP;WIN;COMIC FACES;MEME;RANDOM"
#define appDelegate (AppDelegate*)[[UIApplication sharedApplication] delegate]

@implementation DatabaseConnection


#pragma mark - General Methods for Accessing Core Data
#pragma mark - Read From An Entity



+ (Items*)readFromManagedItem:(NSManagedObject*)managedItem withKeys:(NSArray*)keyArray
{
    Items * item = [[Items alloc] initWithKeys:keyArray];
    for (int i = 0; i < keyArray.count; i++) {
        [item setValue:[managedItem valueForKey:[keyArray objectAtIndex:i]] forKey:[keyArray objectAtIndex:i]];
    }
    
    return [item autorelease];
}

+ (NSMutableArray*)readAllItemsFromEntity:(NSString*)entityName sortWithKey:(NSString*)key ascending:(BOOL)ascending
{
    return [[self class] readItemsFromEntity:entityName withConditionString:nil sortWithKey:key ascending:ascending];
}

+ (NSMutableArray*)readItemsFromEntity:(NSString*)entityName withConditionString:(NSString*)condition sortWithKey:(NSString*)key ascending:(BOOL)ascending
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName 
                                              inManagedObjectContext:[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext]];
    [fetchRequest setEntity:entity];
    
    NSArray * keyArray = [[entity attributesByName] allKeys];
    
    if (condition) {
        NSString * predicateString = condition;
        [fetchRequest setPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@", predicateString]]];
    }
    
    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:ascending];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
	NSError *error = nil;
    [fetchRequest setReturnsObjectsAsFaults:NO];
	NSMutableArray *mutableFetchResults = [[[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] executeFetchRequest:fetchRequest error:&error] mutableCopy];
    
    NSMutableArray * itemsArr = [[NSMutableArray alloc] init];
    
	if (mutableFetchResults != nil) {
        for (int i = 0; i < [mutableFetchResults count]; i++) {
            [itemsArr addObject:[[self class] readFromManagedItem:[mutableFetchResults objectAtIndex:i] withKeys:keyArray]];
        }
	}
    
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];
    
    return [itemsArr autorelease];
}

+ (NSMutableArray*)readItemsFromEntity:(NSString*)entityName withConditionString:(NSString*)condition sortWithKey:(NSString*)key ascending:(BOOL)ascending numberOfRowLimit:(NSNumber*)rows
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
                                              inManagedObjectContext:[appDelegate managedObjectContext]];
    [fetchRequest setEntity:entity];
    
    NSArray * keyArray = [[entity attributesByName] allKeys];
    
    if (condition) {
        NSString * predicateString = condition;
        [fetchRequest setPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@", predicateString]]];
    }
    
    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:ascending];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    if (rows!=nil) {
        [fetchRequest setFetchLimit:[rows intValue]];
    }
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
	NSError *error = nil;
    [fetchRequest setReturnsObjectsAsFaults:NO];
	NSMutableArray *mutableFetchResults = [[[appDelegate managedObjectContext] executeFetchRequest:fetchRequest error:&error] mutableCopy];
//    DBLOG(@"%@",mutableFetchResults);
    NSMutableArray * itemsArr = [[NSMutableArray alloc] init];
    
	if (mutableFetchResults != nil) {
        for (int i = 0; i < [mutableFetchResults count]; i++) {
            [itemsArr addObject:[[self class] readFromManagedItem:[mutableFetchResults objectAtIndex:i] withKeys:keyArray]];
        }
	}
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];
    
    return [itemsArr autorelease];
}


#pragma mark - Write To An Entity

+ (BOOL)writeAnItem:(Items*)item ToEntity:(NSString*)entityName Immediatly:(BOOL)now
{
    NSError * error;
    NSManagedObject * managedItem = nil;
    managedItem = [NSEntityDescription
                   insertNewObjectForEntityForName:entityName
                   inManagedObjectContext:[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext]];
    
    NSArray * keyArray = [item allKeys];
    for (int i = 0; i < keyArray.count; i++) {
        id value = [item valueForKey:[keyArray objectAtIndex:i]];
        if (value) {
            if (![value isEqual:[NSNull null]]) {
                [managedItem setValue:value forKey:[keyArray objectAtIndex:i]];
            }
        }
    }

    if (!now) {
        return YES;
    }
    if (![[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] save:&error]) 
    {
        DBLOG(@"Unresolved error %@, %@", error, [error userInfo]);
        return NO;
    }
    return YES;
}

+ (BOOL)deleteAnItem:(Items*)item ToManagedItem:(NSManagedObject*)managedItem Immediatly:(BOOL)now
{
    NSError * error;
    
    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] deleteObject:managedItem];
    
    if (!now) {
        return YES;
    }
    
    if (![[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] save:&error])
    {
        DBLOG(@"Unresolved error %@, %@", error, [error userInfo]);
        return NO;
    }
    return YES;
}

+ (BOOL)updateAnItem:(Items*)item ToManagedItem:(NSManagedObject*)managedItem Immediatly:(BOOL)now
{
    NSError * error;

    for (NSString *key in [item allKeys]) {
                [managedItem setValue:[item valueForKey:key] forKey:key];
    }
    
    if (!now) {
        return YES;
    }
    
    if (![[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] save:&error]) 
    {
        DBLOG(@"Unresolved error %@, %@", error, [error userInfo]);
        return NO;
    }
    return YES;
}

+ (void)deleteListItems:(NSMutableArray*)list fromEntity:(NSString*)entityName withPrimaryKey:(NSString*)primaryKey
{
    //    assert([NSThread isMainThread]);
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    NSEntityDescription *ent = [NSEntityDescription entityForName:entityName
                                           inManagedObjectContext:[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext]];
    [fetchRequest setEntity:ent];
    
    NSError *error = nil;
    Items *item = [list objectAtIndex:0];
    
    NSArray * keyArray = [item allKeys];
    
    // narrow the fetch to these two properties
    fetchRequest.propertiesToFetch = [NSArray arrayWithObjects:primaryKey, nil];
    
    for (int i=0;i<[list count];i++)
    {
        item = [list objectAtIndex:i];

        fetchRequest.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = '%@'",
                                                                   primaryKey, [item valueForKey:primaryKey]]];
        
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[keyArray objectAtIndex:0] ascending:NO];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        NSArray *fetchedItems = [[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] executeFetchRequest:fetchRequest error:&error];
        if (error) {
            DBLOG(@"err:%@",[error description]);
        }
        if ([fetchedItems count] >0){
            if(![[self class] deleteAnItem:item ToManagedItem:[fetchedItems objectAtIndex:0] Immediatly:NO]){
                DBLOG(@"delete fail");
                return;
            }
        }
    }
    if (![[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] save:&error])
    {
        DBLOG(@"Unresolved error %@, %@", error, [error userInfo]);
        return;
    }
    [fetchRequest release];
    DBLOG(@"DeleteListItemSuccess");
}



+ (void)writeListItems:(NSMutableArray*)list toEntity:(NSString*)entityName withPrimaryKey:(NSString*)primaryKey
{
    //    assert([NSThread isMainThread]);
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *ent = [NSEntityDescription entityForName:entityName
                                           inManagedObjectContext:[appDelegate managedObjectContext]];
    [fetchRequest setEntity:ent];
    
    NSError *error = nil;
    Items *item = [list objectAtIndex:0];
    
    NSArray * keyArray = [item allKeys];
    
    // narrow the fetch to these two properties
    fetchRequest.propertiesToFetch = [NSArray arrayWithObjects:primaryKey, nil];
    
    for (int i=0;i<[list count];i++) 
    {
        item = [list objectAtIndex:i];
//        DBLOG(@"%@",[item allValues]);
        fetchRequest.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = '%@'",
                                  primaryKey, [item valueForKey:primaryKey]]];
        
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[keyArray objectAtIndex:0] ascending:NO];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        NSArray *fetchedItems = [[appDelegate managedObjectContext] executeFetchRequest:fetchRequest error:&error];
        if (error) {
            DBLOG(@"err:%@",[error description]);
        }
        if ([fetchedItems count] == 0)
        {
            // Insert
            if (![[self class] writeAnItem:item ToEntity:entityName Immediatly:NO]){
                DBLOG(@"write fail");
                return;
            }
        }
        else {
            // Update
            if(![[self class] updateAnItem:item ToManagedItem:[fetchedItems objectAtIndex:0] Immediatly:NO]){
                DBLOG(@"update fail");
                return;
            }
        }
    }
    
    [appDelegate saveContext];
    
    [fetchRequest release];
    DBLOG(@"WriteListItemsSuccess");
}

+ (NSInteger)setListItems:(NSMutableArray*)list toEntity:(NSString*)entityName withPrimaryKey:(NSString*)primaryKey
{
    //    assert([NSThread isMainThread]);
    NSInteger count =0;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *ent = [NSEntityDescription entityForName:entityName
                                           inManagedObjectContext:[appDelegate managedObjectContext]];
    [fetchRequest setEntity:ent];
    
    NSError *error = nil;
    Items *item = [list objectAtIndex:0];
    
    NSArray * keyArray = [item allKeys];
    
    // narrow the fetch to these two properties
    fetchRequest.propertiesToFetch = [NSArray arrayWithObjects:primaryKey, nil];
    
    for (int i=0;i<[list count];i++)
    {
        item = [list objectAtIndex:i];
        //        DBLOG(@"%@",[item allValues]);
        fetchRequest.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = '%@'",
                                                                   primaryKey, [item valueForKey:primaryKey]]];
        
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[keyArray objectAtIndex:0] ascending:NO];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        NSArray *fetchedItems = [[[appDelegate managedObjectContext] executeFetchRequest:fetchRequest error:&error] retain];
        if (error) {
            DBLOG(@"err:%@",[error description]);
        }
        if ([fetchedItems count] == 0)
        {
            // Insert
            count ++;
            if (![[self class] writeAnItem:item ToEntity:entityName Immediatly:NO]){
                DBLOG(@"write fail");
                return -1;
            }
        }
        else {
            // Update
            if(![[self class] updateAnItem:item ToManagedItem:[fetchedItems objectAtIndex:0] Immediatly:NO]){
                DBLOG(@"update fail");
                return -1;
            }
        }
    }
    [appDelegate saveContext];

    [fetchRequest release];
    DBLOG(@"WriteListItemsSuccess");
    return count;
}

#pragma mark - App Structure

+(NSInteger)updateListPhotos:(NSMutableArray*)listPhoto{

    DBLOG(@"DatabaseConnection - updateListPhotos:%d",listPhoto.count);
    NSInteger resultCount=[[self class] updateListItems:listPhoto toEntity:@"ManagedTumblrPhoto" withPrimaryKey:@"photoID"];
    
    CMCUniqueArray *uniqueArray=[[CMCUniqueArray alloc] init];
    for (Items *item in listPhoto) {
        NSArray *listTags=[[item valueForKey:@"categoryName"] componentsSeparatedByString:@";"];
        for (NSString *tag in listTags) {
            
            if (![tag isEqualToString:@""] && ![tag isEqualToString:@"(null)"]) {
                [uniqueArray addObject:tag];                
            }
        }
    }
    [[NSUserDefaults standardUserDefaults] setObject:[uniqueArray sortedArray] forKey:@"TAGS_ARRAY"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    return resultCount;
}

+(NSUInteger)updateListItems:(NSMutableArray*)itemsList toEntity:(NSString*)entityName withPrimaryKey:(NSString*)
primaryKey{
    
    NSUInteger successUpdate=0;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    NSEntityDescription *ent = [NSEntityDescription entityForName:entityName
                                           inManagedObjectContext:[appDelegate managedObjectContext]];
    
    NSArray * keyArray = [[ent attributesByName] allKeys];

    
    [fetchRequest setEntity:ent];
    
    NSError *error = NULL;
        
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:primaryKey ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    
    [fetchRequest setSortDescriptors:sortDescriptors];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    
    NSMutableArray *fetchedItems = [[[appDelegate managedObjectContext] executeFetchRequest:fetchRequest error:nil] mutableCopy];
    DBLOG(@"%d",fetchedItems.count);
    if (error) {
        DBLOG(@"err:%@",[error description]);
        return NO;
    }
    NSMutableArray *dbList=[[NSMutableArray alloc] init];
    
    if (fetchedItems != nil) {
        //        DBLOG(@"FETCH NOT NIL");
        
        if (fetchedItems.count==0) {
            for (Items * item in itemsList) {
                if ([[self class] writeAnItem:item ToEntity:entityName Immediatly:NO]){
                    successUpdate++;
                }
            }
        }
        else {
            for (int i = 0; i < [fetchedItems count]; i++) {
                [dbList addObject:[[self class] readFromManagedItem:[fetchedItems objectAtIndex:i] withKeys:keyArray]];
            }
            for (Items *item in itemsList) {
                if ([[self class] findItem:item inListItems:dbList withKey:@"photoID"]==NO) {
                    if ([[self class] writeAnItem:item ToEntity:entityName Immediatly:NO]){
                        successUpdate++;
                    }

                }
            }
        }
        
        
	}
    else {
        DBLOG(@"FETCH NIL");   
    }
    
    
    
    [appDelegate saveContext];
    return YES;

}

+(BOOL)findItem:(Items*)item inListItems:(NSMutableArray*)itemList withKey:(NSString*)key{
    //TODO:Need Implement this function with Binary Search
//    DBLOG(@"findItem:%@",[item valueForKey:key]);
    for (Items *_item in itemList) {
//        DBLOG(@"findList:%@",[_item valueForKey:key]);
        if ([[item valueForKey:key] isEqualToString:[_item valueForKey:key]]) {
//            DBLOG(@"DatabaseConnection - findItem - findSuccess");
            return YES;
        }
    }
    return NO;
}

#pragma mark - Categories

+ (NSMutableArray*)getDefaultCategories{
    NSArray *categoryList=[TAGS_LIST componentsSeparatedByString:@";"];
    NSMutableArray *itemArray=[[NSMutableArray alloc] init];
    NSMutableArray *resultArray=[[NSMutableArray alloc] init];
    for(NSString *categoryName in categoryList){
        
        Category *category=[[Category alloc] init];
        category.categoryName=categoryName;
        category.categoryIsDisplayed=@"YES";
        NSString * conditionString =[NSString stringWithFormat:@"categoryName CONTAINS ';%@;'", [categoryName lowercaseString]];

        NSMutableArray *photoArray=[[[self class] readItemsFromEntity:@"ManagedTumblrPhoto"
                                                  withConditionString:conditionString
                                                          sortWithKey:@"photoCreatedDate"
                                                            ascending:NO
                                                     numberOfRowLimit:[NSNumber numberWithInt:1]]
                                    retain];
        
        if ([photoArray count]>0) {
            Photo *photo=[[Photo alloc] init];
            [photo parseFromItem:(Items*)[photoArray objectAtIndex:0]];
//            DBLOG(@"%@",photo.photoImage);
            category.categoryThumbnailPath =photo.photo250URL;
            [photo release];
        }
        else{
            category.categoryThumbnailPath=@"";
        }
        
        [itemArray addObject:[category itemObject]];
        [resultArray addObject:category];
        [category release];
    }
    
//    [self writeListItems:itemArray toEntity:@"ManagedCategory" withPrimaryKey:@"categoryName"];
    
    
    return [resultArray autorelease];
}

#pragma mark - Tumblr Photos

+ (NSMutableArray *)getRecentlyAddedPhotos{
    
//    2012-09-21 16:38:07 GMT
    
    NSString * conditionString =[NSString stringWithFormat:@"photoCreatedDate > '1970-01-01 00:00:00 GMT'"];
    NSMutableArray * listItem = [[self class] readItemsFromEntity:@"ManagedTumblrPhoto"
                                              withConditionString:conditionString
                                                      sortWithKey:@"photoCreatedDate"
                                                        ascending:NO
                                                 numberOfRowLimit:[NSNumber numberWithInt:60]];
    
    NSMutableArray * listPhoto = [[NSMutableArray alloc] init];
    for (Items * item in listItem) {
        Photo* photo = [[Photo alloc] init];
        [photo parseFromItem:item];
        NSLog(@"%@",photo.photoCreatedDate);

        [listPhoto addObject:photo];
        [photo release];
    }
    return [listPhoto autorelease];
}

+ (NSMutableArray *)getRecentlyUsedPhotos{
    NSString * conditionString =[NSString stringWithFormat:@"photoRecentlyUsed > '19990102030405'"];
    
    NSMutableArray * listItem = [[self class] readItemsFromEntity:@"ManagedTumblrPhoto"
                                              withConditionString:conditionString
                                                      sortWithKey:@"photoRecentlyUsed"
                                                        ascending:NO];
    
    NSMutableArray * listPhoto = [[NSMutableArray alloc] init];
    for (Items * item in listItem) {
        Photo* photo = [[Photo alloc] init];
        [photo parseFromItem:item];
        [listPhoto addObject:photo];
        [photo release];
    }
    return [listPhoto autorelease];
}


+ (NSMutableArray *)getTumblrPhotosWithTag:(NSString*)_tag{
    NSString * conditionString =[NSString stringWithFormat:@"categoryName CONTAINS '%@'", [_tag lowercaseString]];
    NSMutableArray * listItem = [[self class] readItemsFromEntity:@"ManagedTumblrPhoto"
                                              withConditionString:conditionString
                                                      sortWithKey:@"photoCreatedDate"
                                                        ascending:NO];
    NSMutableArray * listPhoto = [[NSMutableArray alloc] init];
    for (Items * item in listItem) {
        Photo* photo = [[Photo alloc] init];
        [photo parseFromItem:item];
//        DBLOG(@"%@",photo.photoName);
        [listPhoto addObject:photo];
        [photo release];
    }
    return [listPhoto autorelease];
}

#pragma mark - Favorite Photos

+ (NSMutableArray *)getFavoritePhotos{
    NSMutableArray * listItem = [[self class] readAllItemsFromEntity:@"ManagedFavoritePhoto"
                                                         sortWithKey:@"photoCreatedDate"
                                                           ascending:NO];
    
    NSMutableArray * listPhoto = [[NSMutableArray alloc] init];
    for (Items * item in listItem) {
        Photo* photo = [[Photo alloc] init];
        [photo parseFromItem:item];
//        DBLOG(@"%@",photo.photoImage);
        [listPhoto addObject:photo];
        [photo release];
    }
    return [listPhoto autorelease];
}

+ (NSMutableArray *)getFavoritePhotoWithID:(NSString*)_photoID{
    
    NSString * conditionString =[NSString stringWithFormat:@"photoID = '%@'", _photoID];
    
    NSMutableArray * listItem = [[self class] readItemsFromEntity:@"ManagedFavoritePhoto"
                                              withConditionString:conditionString
                                                      sortWithKey:@"photoCreatedDate"
                                                        ascending:YES];
    
    NSMutableArray * listPhoto = [[NSMutableArray alloc] init];
    for (Items * item in listItem) {
        Photo* photo = [[Photo alloc] init];
        [photo parseFromItem:item];
        //        DBLOG(@"%@",photo.photoName);
        [listPhoto addObject:photo];
        [photo release];
    }
    return [listPhoto autorelease];
}

+(BOOL)isAddedToFavoriteWithPhotoID:(NSString*)_photoID{
   if ([[[self class] getFavoritePhotoWithID:_photoID] count]>0)
       return YES;
    else
        return NO;
}


#pragma mark - Custom Photos

+ (NSMutableArray *)getCustomsPhotos{
    NSMutableArray * listItem = [[self class] readAllItemsFromEntity:@"ManagedCustomPhoto"
                                                         sortWithKey:@"photoCreatedDate"
                                                           ascending:NO];
    
    NSMutableArray * listPhoto = [[NSMutableArray alloc] init];
    for (Items * item in listItem) {
        Photo* photo = [[Photo alloc] init];
        [photo parseFromItem:item];
        //        DBLOG(@"%@",photo.photoName);
        [listPhoto addObject:photo];
        [photo release];
    }
    return [listPhoto autorelease];
}

+(BOOL)writeToCustomPhotoWithImage:(UIImage*)_image{
    NSString * photoID=[Utilities uniqueStringWithPrefix:@""];
    NSString * saveName=[NSString stringWithFormat:@"M%@_%@_MEME.png",photoID,photoID];
//    NSString * thumbnailName=[NSString stringWithFormat:@"M%@_%@_MEMETHUMB.png",photoID,photoID];

    [Utilities saveImage:_image
     toDocumentSubFolder:@"Meme"
                withName:saveName];
//    [Utilities saveImage:[Utilities resizedImage:_image withRect:CGRectMake(0, 0, 200, 200)]
//     toDocumentSubFolder:@"MemeThumbnail"
//                withName:thumbnailName];
//    
    Photo *photo=[[Photo alloc] init];
    
    [photo setPhotoID:photoID];
    [photo setPhotoImage:[[NSURL fileURLWithPath:[[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Meme"] stringByAppendingPathComponent:saveName]] absoluteString]];
//    [photo setPhotoThumbnail:[[NSURL fileURLWithPath:[[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"MemeThumbnail"] stringByAppendingPathComponent:thumbnailName]] absoluteString]];
    [photo setPhotoThumbnail:photo.photoImage];
    [photo setPhotoDownloaded:[NSNumber numberWithInt:1] ];
    [photo setPhotoCreatedDate:photoID];
    
    [photo setPhotoName:saveName];
    [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedCustomPhoto" withPrimaryKey:@"photoID"];
    [photo release];
    return YES;
}

+(BOOL)updateToCustomPhoto:(Photo*)photo
                 withImage:(UIImage*)_image{
    NSString * photoID=photo.photoID;
    
    NSString * saveName=[NSString stringWithFormat:@"M%@_%@_MEME.png",photoID,photoID];
//    NSString * thumbnailName=[NSString stringWithFormat:@"M%@_%@_MEMETHUMB.png",photoID,photoID];
    [[NSFileManager defaultManager] removeItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:saveName] error:nil];
    [Utilities saveImage:_image
     toDocumentSubFolder:@"Meme"
                withName:saveName];
//    [Utilities saveImage:[Utilities resizedImage:_image withRect:CGRectMake(0, 0, 200, 200)]
//     toDocumentSubFolder:@"MemeThumbnail"
//                withName:thumbnailName];
    return YES;
}

@end
